﻿using System;
using System.ComponentModel;
using System.Windows.Forms;

using ExtensibleEventViewer.Console.EventArguments;


namespace ExtensibleEventViewer.Console.Forms
{
	public partial class TimePeriodWnd : FormBase
	{
		public EventHandler Cancel;

		public EventHandler<SaveTimePeriodEventArgs> SaveTimePeriod;

		public TimePeriodWnd()
		{
			InitializeComponent();

			timePeriodControl.Validating += TimePeriodControlValidating;
		}

		void TimePeriodControlValidating(object sender, CancelEventArgs e)
		{
			if (cbEnableAutoRefresh.Checked)
			{
				if (timePeriodControl.TimePeriod.TotalSeconds == 0)
				{
					timePeriodControl.InvalidateTimePeriod();

					e.Cancel = true;

					return;
				}
			}

			e.Cancel = false;
		}

		public void LoadData(TimeSpan autoRefreshPeriod, bool enableAutoRefresh)
		{
			timePeriodControl.TimePeriod = autoRefreshPeriod;
			cbEnableAutoRefresh.Checked = enableAutoRefresh;

			EnableAutoRefreshCheckedChanged(this, EventArgs.Empty);
		}

		private void CancelClick(object sender, EventArgs e)
		{
			DialogResult = DialogResult.Cancel;

			if (Cancel != null)
			{
				Cancel(this, EventArgs.Empty);
			}

			Close();
		}

		private void SaveClick(object sender, EventArgs e)
		{
			DialogResult = DialogResult.OK;

			if (SaveTimePeriod != null)
			{
				SaveTimePeriodEventArgs eventArgs = new SaveTimePeriodEventArgs
				                                    	{
				                                    		TimePeriod = timePeriodControl.TimePeriod,
															EnableAutoRefresh = cbEnableAutoRefresh.Checked
				                                    	};

				SaveTimePeriod(this, eventArgs);
			}

			Close();
		}

		private void EnableAutoRefreshCheckedChanged(object sender, EventArgs e)
		{
			timePeriodControl.Enabled = cbEnableAutoRefresh.Checked;
		}
	}
}
